﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;

//using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;

using Baosight.ZNH.ZMCA.UI.Controls;
using Baosight.ZNH.ZMCA.UI.Utils;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Gauges;
using Telerik.Windows.Controls.Charting;
using Baosight.ZNH.ZMCA.UI.Model;

namespace Baosight.ZNH.ZMCA.UI
{
    public partial class ZMCA01 : EFView
    {
        public ZMCA01Controler controler = new ZMCA01Controler();

        public ZMCA01()
        {
            InitializeComponent();

            InitGaugeData(this.indexGauge);
            InitChartData(this.tendChart);
            InitRadTreeListData(this.lstView);

        }

        #region 填充控件数据

        private void InitGaugeData(DoubleCircleGauge gauge)
        {
            controler.GetGaugeData(gauge);
        }

        private void InitChartData(RadChart chart)
        {
            controler.GetChartData(chart);
        }

        private void InitRadTreeListData(RadTreeListView lstView)
        {
            controler.GetRadTreeListData(lstView);
        }

        #endregion

    }



    public class ZMCA01Controler
    {
        private DoubleCircleGauge gauge;
        private RadChart chart;
        private RadTreeListView lstView;
        private int empCount = 0;   //记录全矿当前人数

        public ZMCA01Controler()
        {

        }

        #region 查询加载Gauge图

        /// <summary>
        /// 初始化指标图，查询数据
        /// </summary>
        public void GetGaugeData(DoubleCircleGauge gauge)
        {
            this.gauge = gauge;
            this.gauge.gaugeTitle.Text = "回采工作面效率";

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA01");
            eiInfo.Set("method", "queryByIndex");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, QueryGaugeDataDoWorkCompleted);
        }

        /// <summary>
        /// 查询指标图数据回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryGaugeDataDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo eiInfo = e.EIInfo;
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }

            EIBlock result = eiInfo.GetBlock("result");

            int yearPerson = int.Parse(eiInfo.Get("YearPerson").ToString());
            int monthPerson = int.Parse(eiInfo.Get("MonthPerson").ToString());
            int currentMonth = int.Parse(eiInfo.Get("month").ToString());
            int currentYear = int.Parse(eiInfo.Get("year").ToString());
            int dayOfYear = DateTime.IsLeapYear(currentYear) ? 366 : 365;
            int dayOfMonth = DateTime.DaysInMonth(currentYear, currentMonth);

            double yearPlan = 0;
            double yearActual = 0;
            double monthPlan = 0;
            double monthAcutal = 0;

            if (result != null && result.Rows.Count > 0)
            {
                foreach (var item in result.Rows)
                {
                    int dataType = Common.GetIntValue(item["fdPlanType"]);
                    //通过dataType判断数据类型,0年计划， 1月计划，20年实际， 30月实际， 35昨日计划， 40昨日
                    if (dataType == 0)
                    {
                        yearPlan = Common.GetDoubleValue(item["fdPlanMine"]);
                    }
                    else if (dataType == 1)
                    {
                        monthPlan = Common.GetDoubleValue(item["fdPlanMine"]);
                    }
                    else if (dataType == 20)
                    {
                        yearActual = Common.GetDoubleValue(item["fdPlanMine"]);
                    }
                    else if (dataType == 30)
                    {
                        monthAcutal = Common.GetDoubleValue(item["fdPlanMine"]);
                    }           
                }
            }
            if (monthPerson != 0)
            {
                monthPlan = monthPlan / monthPerson;
                monthAcutal = monthAcutal / monthPerson;
            }
            if (yearPerson != 0)
            {
                yearPlan = yearPlan / yearPerson;
                yearActual = yearActual / yearPerson;
            }
            
            //计算单位，并将指标值缩小到100以内
            int monthUnit = ZMCA03Controler.GetUnit(monthAcutal);
            int yearUnit = ZMCA03Controler.GetUnit(yearActual);

            monthPlan = monthPlan / monthUnit;
            yearPlan = yearPlan / yearUnit;

            monthAcutal = monthAcutal / monthUnit;
            yearActual = yearActual / yearUnit;

            //设置最大值

            string unit = "吨";
            gauge.leftGaugeDescription.Text = yearUnit >= 10 ? Common.GetChineseUnit(yearUnit) + unit + "/人天（年）" : unit + "/人天（年）";
            gauge.rightGaugeDescription.Text = monthUnit >= 10 ? Common.GetChineseUnit(monthUnit) + unit + "/人天（月）" : unit + "/人天（月）";
            gauge.leftNeedle.Value = yearActual;
            gauge.rightNeedle.Value = monthAcutal;

        }

        #endregion


        #region 查询加载Chart图

        /// <summary>
        /// 初始化趋势图，查询数据
        /// </summary>
        public void GetChartData(RadChart chartIndex)
        {
            this.chart = chartIndex;

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA01");
            eiInfo.Set("method", "queryByChart");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, QueryChartDataDoWorkCompleted);
        }

        /// <summary>
        /// 查询趋势图数据回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryChartDataDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                return;
            }
            else
            {
                EIInfo eiInfo = e.EIInfo;
                EIBlock queryByChart = eiInfo.GetBlock("queryByChartB");
                decimal yearPerson, monthPerson;
                int currentMonth = int.Parse(eiInfo.Get("month").ToString());
                int currentYear = int.Parse(eiInfo.Get("year").ToString());
                int dayOfYear = DateTime.IsLeapYear(currentYear) ? 366 : 365;


                chart.DefaultView.ChartTitle.Content = currentYear + "回采工作面效率趋势分析";
                chart.DefaultSeriesDefinition.ShowItemToolTips = true;
                chart.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;
                chart.DefaultView.ChartLegend.Header = "单位：吨/人天";

                this.chart.DefaultView.ChartTitle.FontSize = Common.FontsizeSetting + 2;
                this.chart.DefaultView.ChartArea.FontSize = Common.FontsizeSetting;
                this.chart.DefaultView.ChartLegend.FontSize = Common.FontsizeSetting - 2;

                this.chart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
                this.chart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
                this.chart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

                SeriesMapping sm1 = Common.AddBarToChart("回采工作面效率", 0);
                chart.SeriesMappings.Add(sm1);

                List<List<ChartData>> itemsSource = new List<List<ChartData>>();
                List<ChartData> lstActual = new List<ChartData>();

                for (int i = 1; i <= currentMonth; i++)
                {
                    lstActual.Add(new ChartData(i + "月", 0));
                }
                lstActual.Add(new ChartData("全年", 0));

                //fdPlanType: 0年计划， 1月计划，20年实际， 30月实际， 40昨日
                foreach (var item in queryByChart.Rows)
                {
                    if (item["fdPlanYear"].ToString().Trim() == string.Empty)
                    {
                        continue;
                    }
                    int dataType = Common.GetIntValue(item["fdPlanType"]);
                    int month = Common.GetIntValue(item["fdPlanMonth"]);
                    if (month == 0)
                    {
                        yearPerson = Common.GetDecimalValue(item["fdPlanProjectNum"]);
                        if (yearPerson != 0)
                            lstActual[lstActual.Count - 1].DataValue = Common.GetDecimalValue(item["fdActualSum"]) / yearPerson;
                        else
                            lstActual[lstActual.Count - 1].DataValue = 0;
                    }
                    else if (month <= currentMonth)
                    {
                        int dayOfMonth = DateTime.DaysInMonth(currentYear, month);
                        monthPerson = Common.GetDecimalValue(item["fdPlanProjectNum"]);
                        if (monthPerson != 0)
                            lstActual[month - 1].DataValue = Common.GetDecimalValue(item["fdActualSum"]) / monthPerson;
                        else
                            lstActual[month - 1].DataValue = 0;
                    }
                }

                itemsSource.Add(lstActual);
                chart.ItemsSource = itemsSource;
            }
        }


        #endregion


        #region 查询加载RadTreeListView及数据

        public void GetRadTreeListData(RadTreeListView lstView)
        {
            this.lstView = lstView;

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA01");
            eiInfo.Set("method", "queryByListView");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, QueryListViewDataDoWorkCompleted);
        }

        private void QueryListViewDataDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                return;
            }
            else
            {
                EIInfo eiInfo = e.EIInfo;
                EIBlock queryByChart = eiInfo.GetBlock("queryByChartB");
                EIBlock queryByWorkFaceEff = eiInfo.GetBlock("queryByWorkFaceEff");
                
         //       int empCount = int.Parse(eiInfo.Get("empCount").ToString());
                decimal yearPerson, monthPerson;
                int currentMonth = int.Parse(eiInfo.Get("month").ToString());
                int currentYear = int.Parse(eiInfo.Get("year").ToString());
                int dayOfYear = DateTime.IsLeapYear(currentYear) ? 366 : 365;

                //将超过当前月的列隐藏
                for (int i = 12 - currentMonth + 1; i > 1; i--)
                {
                    var col = lstView.Columns[i];
                    col.IsVisible = false;
                }

                //构造树目录结构
                List<ZMCA03DetailItem> itemsSource = new List<ZMCA03DetailItem>();


                ZMCA03DetailItem yearItem = new ZMCA03DetailItem();
                Type itemType = yearItem.GetType();
                itemsSource.Add(yearItem);
                yearItem.Name = "全矿";

                foreach (var item in queryByChart.Rows)
                {
                    if (item["fdPlanYear"].ToString().Trim() == string.Empty)
                    {
                        continue;
                    }
                    int dataType = Common.GetIntValue(item["fdPlanType"]);
                    int month = Common.GetIntValue(item["fdPlanMonth"]);
                    if (month == 0)
                    {
                        yearPerson = Common.GetDecimalValue(item["fdPlanProjectNum"]);
                        if (yearPerson != 0)
                        {
                            yearItem.DependantTotalYear = Common.GetDecimalValue(item["fdActualSum"]) / yearPerson;
                        }
                        else
                        {
                            yearItem.DependantTotalYear = 0;
                        }
                    }
                    else if (month <= currentMonth)
                    {
                        monthPerson = Common.GetDecimalValue(item["fdPlanProjectNum"]);
                        PropertyInfo pi = itemType.GetProperty("M" + month);
                        if (monthPerson != 0)
                        {
                            pi.SetValue(yearItem, Common.GetDecimalValue(item["fdActualSum"]) / monthPerson, null);
                        }
                        else
                        {
                            pi.SetValue(yearItem, decimal.Zero, null);
                        }
                    }
                }

                AddChildItemByBlock(queryByWorkFaceEff, yearItem, itemType, "fdWorkface", currentMonth);

                lstView.ItemsSource = itemsSource;
            }
        }

        private void AddChildItemByBlock(EIBlock block, ZMCA03DetailItem parentDetailItem, Type itemType, string UniqueColumnName, int currentMonth)
        {
            ZMCA03DetailItem detailItem = null;
            Dictionary<string, ZMCA03DetailItem> dic = new Dictionary<string, ZMCA03DetailItem>();
            foreach (var item in block.Rows)
            {
                string year = item["fdPlanYear"].ToString();
                if (year.Trim() == string.Empty)
                {
                    continue;
                }
                string itemUniqueName = Common.GetStringValue(item[UniqueColumnName]);
                if (detailItem == null || detailItem.UniqueName != itemUniqueName)
                {
                    detailItem = new ZMCA03DetailItem();
                    parentDetailItem.Items.Add(detailItem);
                    detailItem.UniqueName = itemUniqueName;
                    detailItem.Name = Common.GetStringValue(item[UniqueColumnName]);
                    dic.Add(itemUniqueName, detailItem);
                }

                int month = Common.GetIntValue(item["fdPlanMonth"]);
                if (month == 0)
                {
                    decimal yearPerson = Common.GetDecimalValue(item["fdPlanProjectNum"]);
                    if (yearPerson != 0)
                    {
                        detailItem.DependantTotalYear = Common.GetDecimalValue(item["fdActualSum"]) / yearPerson;
                    }
                    else
                    {
                        detailItem.DependantTotalYear = 0;
                    }
                }
                else if (month <= currentMonth)
                {
                    decimal monthPerson = Common.GetDecimalValue(item["fdPlanProjectNum"]);
                    PropertyInfo pi = itemType.GetProperty("M" + month);
                    if (monthPerson != 0)
                    {
                        pi.SetValue(detailItem, Common.GetDecimalValue(item["fdActualSum"]) / monthPerson, null);
                    }
                    else
                    {
                        pi.SetValue(detailItem, decimal.Zero, null);
                    }
                }
            }

            //ZMCA03DetailItem.SummarizedChildItemData(parentDetailItem);
        }


        #endregion
    }
}
